<template>
  <div id='params'>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader expand-trigger="hover" :options="cateList" :props="cateProps" v-model="selectedCateKeys"
            @change="handleChange"></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加参数
          </el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <!-- 展开行 -->
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">
                  {{item}}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加属性
          </el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <!-- 展开行 -->
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">
                  {{item}}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog :title="'添加'+titleText" :visible="addDialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="90px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addParams">确 定</el-button>
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog :title="'修改'+titleText" :visible="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="90px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editParams">确 定</el-button>
        <el-button @click="editDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: 'params',
    data() {
      return {
        //  所有商品分类列表
        cateList: [],
        // 级联选择框的配置对象
        cateProps: {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        // 级联选择框双向绑定到的数组
        selectedCateKeys: [],
        // 被激活的页签的名称
        activeName: "many",
        // 动态参数列表
        manyTableData: [],
        // 静态属性列表
        onlyTableData: [],
        // 控制添加对话框的显示与隐藏
        addDialogVisible: false,
        // 添加参数的表单对象
        addForm: {
          attr_name: ''
        },
        // 添加参数的验证规则
        addFormRules: {
          attr_name: [{
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }]
        },
        // 控制修改对话框的显示与隐藏
        editDialogVisible: false,
        // 修改表单的数据对象
        editForm: {},
        // 修改参数的验证规则
        editFormRules: {
          attr_name: [{
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }]
        },
      }
    },
    created() {
      this.getCateList()
    },
    computed: {
      // 如果按钮被禁用返回true
      isBtnDisabled() {
        if (this.selectedCateKeys.length !== 3) {
          return true
        }
        return false
      },
      // 当前选中的三级分类的id
      cateId() {
        if (this.selectedCateKeys.length = 3) {
          return this.selectedCateKeys[2]
        }
        return null
      },
      // 动态计算标题的文本
      titleText() {
        if (this.activeName === 'many') {
          return '动态参数'
        } else {
          return '静态属性'
        }
      }
    },
    methods: {
      // 获取所有商品分类列表
      async getCateList() {
        await this.$http.get('categories').then(res => {
          if (res.data.meta.status == 200) {
            this.cateList = res.data.data
          } else {
            this.$message({
              message: res.data.meta.msg,
              type: 'error',
              duration: 20000
            })
          }
        })
      },
      // 获取参数的列表数据
      async getParamsData() {
        //   选择的不是三级分类
        if (this.selectedCateKeys.length != 3) {
          this.selectedCateKeys = []
          this.manyTableData = []
          this.onlyTableData = []
          return
        }
        // 如果是三级分类则根据所选分类的id和当前所处的tab面板获取参数
        await this.$http.get(`categories/${this.cateId}/attributes`, {params: {sel: this.activeName}}).then(res => {
          if (res.data.meta.status == 200) {
            // 将参数的attr_vals分割成数组，在通过for循环转化为一个个的tag标签
            res.data.data.forEach(item =>{
              // 空的字符串分割时会返回[""]，如果该字符串不为空则做分割，为空则返回空字符串
              item.attr_vals = item.attr_vals?item.attr_vals.split(' '):[]
              // 便于单独控制每一个参数下文本框与按钮的显示与隐藏
              // 控制文本框的显示与隐藏
              item.inputVisible = false
              // 默认文本框的内容为空
              item.inputValue = ''
            })
            // 获取到的是动态参数的数据
            if (this.activeName === 'many') {
              this.manyTableData = res.data.data
            } else {
              this.onlyTableData = res.data.data
            }
          } else {
            this.$message({
              message: res.data.meta.msg,
              type: 'error',
              duration: 20000
            })
          }
        })
      },
      // 级联选择框选中项发生变化时触发的事件
      handleChange() {
        this.getParamsData()
      },
      //   tab页签点击事件的处理函数
      handleTabClick() {
        this.getParamsData()
      },
      // 监听添加参数对话框的关闭事件
      addDialogClosed() {
        this.$refs.addFormRef.resetFields()
        this.addDialogVisible = false
      },
      // 添加参数
      async addParams() {
        this.$refs.addFormRef.validate(async (valid) => {
          if (valid) {
            await this.$http.post(`categories/${this.cateId}/attributes`, {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName
            }).then(res => {
              if (res.data.meta.status == 201) {
                this.$message({
                  type: 'success',
                  message: res.data.meta.msg,
                  duration: 600
                })
                this.getParamsData()
                this.addDialogVisible = false
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.meta.msg,
                  duration: 20000
                })
              }
            })
          } else {
            return
          }
        })
      },
      // 显示编辑对话框
      async showEditDialog(attr_id) {
        await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`, {params:{attr_sel: this.activeName}}).then(res => {
          if (res.data.meta.status == 200) {
            this.editForm = res.data.data
          } else {
            this.$message({
              message: res.data.meta.msg,
              type: 'error',
              duration: 20000
            })
          }
        })
        this.editDialogVisible = true
      },
      // 监听编辑参数对话框的关闭事件
      editDialogClosed() {
        this.$refs.editFormRef.resetFields()
        this.editDialogVisible = false
      },
      // 编辑参数
      async editParams() {
        this.$refs.editFormRef.validate(async (valid) => {
          if (valid) {
            await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {attr_name:this.editForm.attr_name,attr_sel:this.activeName}).then(res => {
              if (res.data.meta.status == 200) {
                this.$message({
                  message: res.data.meta.msg,
                  type: 'success',
                  duration: 600
                })
                this.getParamsData()
                this.editDialogVisible = false
              } else {
                this.$message({
                  message: res.data.meta.msg,
                  type: 'error',
                  duration: 20000
                })
              }
            })
          } else {
            return
          }
        })
      },
      // 删除参数
      removeParams(attr_id){
        this.$confirm('确定删除改参数吗？','提示',{
          confirmButtonText:'确定',
          cancleButtonText:'取消',
          type:'warning'
        }).then(()=>{
          this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`).then(res => {
            if(res.data.meta.status == 200){
              this.$message({
                type:'success',
                message:res.data.meta.msg,
                duration:600
              })
              this.getParamsData()
            }else{
              this.$message({
                type:'error',
                message:res.data.meta.msg,
                duration:2000
              })
            }
          })
        }).catch(err => {
          return err
        })
      },
      // 文本框失去焦点或按下enter键触发事件
      async handleInputConfirm(row){
        // 输入框无实际内容直接重置
        if(row.inputValue.trim().length === 0){
          row.inputValue = ''
          row.inputVisible = false
          return
        }
        // 文本框有输入内容时将内容push到attr_vals数组中
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        // 保存到数据库
        this.saveAttrValues(row)
      },
      // 点击按钮显示文本框
      showInput(row){
        row.inputVisible = true
        // 将inputVisible值修改为true之后页面上的元素还没有被重新渲染，即页面上展示的还是button按钮，并不是文本框，
        // 当$nextTick方法被调用才证明页面上的元素已经被重新渲染
        // $nextTick方法的作用：当页面上元素被重新渲染之后才会执行回调函数的代码，防止通过refs找不到对应的元素
        this.$nextTick(_ => {
          // 使文本框获得焦点
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      // 删除tag参数
      handleClose(index,row){
        // 从数组中根据索引删除对应参数
        row.attr_vals.splice(index,1)
        // 保存到数据库
        this.saveAttrValues(row)
      },
      // 保存attr_vals - tag参数保存到数据库
      async saveAttrValues(row){
        // 保存到数据库
        await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{attr_name:row.attr_name,attr_sel:row.attr_sel,attr_vals:row.attr_vals.join(' ')}).then(res => {
          if(res.data.meta.status == 200){
            this.$message({
              type:'success',
              message:res.data.meta.msg,
              duration:600
            })
          }else{
            this.$message({
              type:'error',
              message:res.data.meta.msg,
              duration:2000
            })
          }
        })
      }
    }
  }

</script>
<style scoped>
  .cat_opt {
    margin: 15px 0;
  }
  .el-tag{
    margin: 10px;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
</style>
